﻿using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using OznerOA.Common;
using OznerOA.Model.Wechat;
using OznerOA.Utils;
using System;
using System.Collections.Generic;
using System.Drawing; 
using System.Linq;
using System.Text.RegularExpressions;

namespace OznerOA.BLL
{ 
    public class WechatBLL : BaseBLL
    {
        #region 自己的代码

        private string UUID = null;
        private string InitUrl = null;
        private LoginInfo LoginInfo = null;
        private Contract User = null;
        #region 获取微信的UUID
        private BaseResult<T> GetUUID<T>(bool refresh)
        {
            //强制刷新掉二维码
            if (refresh) UUID = null;
            BaseResult<T> br = new BaseResult<T>();
            if (string.IsNullOrEmpty(UUID))
            {
                string URL = string.Format("https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&fun=new&lang=zh_CN&_={0}", DateUtils.GetTimestamp(DateTime.Now));
                HttpBaseResult hbr = HttpHelper.HttpGetHtml(URL, "");

                if (hbr.Code == 200)
                {
                    Dictionary<string, string> response = ParseResponse(hbr.Html);
                    if (response.ContainsKey("window.QRLogin.uuid"))
                    {
                        //获取UUID
                        UUID = response["window.QRLogin.uuid"];
                        if (!string.IsNullOrEmpty(UUID))
                        {
                            br.Code = Code.OK;
                        }
                        else
                        {
                            br.Code = Code.OK;
                            br.Message = "获取UUID失败!";
                        }
                    }
                }
                else
                {
                    br.Code = Code.NULL;
                    br.Message = "网络连接失败!";
                }
            }
            else
            {
                br.Code = Code.OK;
            }
            return br;
        }

        #endregion
        #region 获取微信登录二维码
        public BaseResult<Image> GetLoginGrcode(bool refreshUUID)
        {
            BaseResult<Image> br = GetUUID<Image>(refreshUUID);
            if (br.Code == Code.OK)
            {
                string URL = string.Format("https://login.weixin.qq.com/qrcode/{0}", UUID);
                HttpBaseResult hbr = HttpHelper.HttpGetByteOrImage(URL, "");
                if (hbr.Code == 200)
                {
                    br.Object = hbr.Image;
                }
                else
                {
                    br.Code = Code.NULL;
                    br.Message = "获取二维码失败!";
                }
            }
            return br;
        }
        #endregion
        #region 解析请求结果
        private Dictionary<string, string> ParseResponse(string response)
        {
            Dictionary<string, string> res = new Dictionary<string, string>();
            //先将单引号或双引号中的内容替换
            string reg = "(['\"])(?:(?!\\1).)*?\\1";
            MatchCollection matchs = Regex.Matches(response, reg);
            for (int i = 0; i < matchs.Count; i++)
            {
                Match match = matchs[i];
                response = response.Replace(match.Value, "{" + i + "}");
            }


            //以';'进行分割
            string[] strSplit = response.Split(';');
            //遍历结果
            foreach (string str in strSplit)
            {
                //截取key和value
                if (str.Contains("="))
                {
                    int index = str.IndexOf('=');
                    string key = str.Substring(0, index);
                    string value = str.Substring(index + 1);
                    //value引号内容替换进行替换
                    for (int i = 0; i < matchs.Count; i++)
                    {
                        if (value.Contains("{" + i + "}"))
                        {
                            value = value.Replace("{" + i + "}", matchs[i].Value);
                        }
                    }
                    res.Add(key.Trim(), value.Replace("\"", "").Replace("'", "").Trim());
                }
            }

            return res;
        }

        #endregion
        #region 检测是否扫描二维码和登录
        public BaseResult<Dictionary<string, string>> GetLoginInfo(string tip)
        {
            BaseResult<Dictionary<string, string>> res = new BaseResult<Dictionary<string, string>>();
            string URL = string.Format("https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip={1}&_={2}", UUID, tip, DateUtils.GetTimestamp(DateTime.Now));
            HttpBaseResult hbr = HttpHelper.HttpGetHtml(URL, "");
            if (hbr.Code == 200)
            {
                res.Code = Code.OK;
                res.Object = ParseResponse(hbr.Html);
                if (res.Object["window.code"] == "200")
                {
                    InitUrl = res.Object["window.redirect_uri"];
                }
            }
            else
            {
                res.Code = Code.NULL;
                res.Message = "网络连接失败!" + hbr.Code + ":" + hbr.Description;
            }
            return res;
        }
        #endregion
        #region 微信初始化
        public BaseResult<Contract> Init()
        {
            BaseResult<Contract> br = new BaseResult<Contract>();
            if (!string.IsNullOrEmpty(InitUrl))
            {
                HttpBaseResult hbr = HttpHelper.HttpGetHtml(InitUrl + "&fun=new&version=v2", "");
                if (hbr.Code == 200)
                {
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(hbr.Html);
                    HtmlNode hnRet = doc.DocumentNode.SelectSingleNode("//error/ret");
                    if (hnRet != null && hnRet.InnerText == "0")
                    {
                        LoginInfo = new LoginInfo();
                        //封装LoginInfo
                        HtmlNode hnWxsid = doc.DocumentNode.SelectSingleNode("//error/wxsid");
                        HtmlNode hnWxuin = doc.DocumentNode.SelectSingleNode("//error/wxuin");
                        HtmlNode hnSky = doc.DocumentNode.SelectSingleNode("//error/skey");
                        HtmlNode hnPassTicket = doc.DocumentNode.SelectSingleNode("//error/pass_ticket");
                        if (hnWxsid != null) LoginInfo.Wxsid = hnWxsid.InnerText;
                        if (hnWxuin != null) LoginInfo.Wxuin = hnWxuin.InnerText;
                        if (hnSky != null) LoginInfo.Skey = hnSky.InnerText;
                        if (hnPassTicket != null) LoginInfo.PassTicket = hnPassTicket.InnerText;

                        //访问初始化地址
                        if (!string.IsNullOrEmpty(LoginInfo.PassTicket))
                        {
                            string url = string.Format("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r={0}&lang=ch_ZN&pass_ticket={1}", DateUtils.GetTimestamp(DateTime.Now), LoginInfo.PassTicket);
                            var postdata = new { BaseRequest = new { Uin = LoginInfo.Wxuin, Sid = LoginInfo.Wxsid, Skey = LoginInfo.Skey, DeviceID = "e" + NumberUtils.Random(15) } };
                            HttpBaseResult hb = HttpHelper.HttpPostPayload(url, "", postdata);
                            if (hb.Code == 200)
                            {
                                JObject jObject = JObject.Parse(hb.Html);

                                InitResponse response = jObject.ToObject<InitResponse>();
                                User = response.User;
                            }
                            else
                            {
                                br.Code = Code.NULL;
                                br.Message = hb.Description;
                            }
                        }
                        else
                        {
                            br.Code = Code.NULL;
                            br.Message = "获取登录信息失败";
                        }
                    }
                    else
                    {
                        br.Code = Code.NULL;
                        br.Message = doc.DocumentNode.SelectSingleNode("//error/message").InnerText;
                    }
                }
                else
                {
                    br.Code = Code.NULL;
                    br.Message = hbr.Description;
                }
            }
            else
            {
                br.Code = Code.NULL;
                br.Message = "您尚未登录，请先登录!";
            }
            return null;
        }
        #endregion
        #region 获取联系人
        public BaseResult<List<Contract>> GetContracts()
        {
            return null;
        }
        #endregion
        #endregion
    }
}
